
var edit_add_images='edit_add_images';
var u2b='u2b';
var article='article';
var edit_add_fb_cmts='edit_add_fb_cmts';

var a_edit_add_images='a_'+edit_add_images;
var div_edit_add_images='div_'+edit_add_images;
var a_u2b='a_'+u2b;
var div_u2b='div_'+u2b;
var a_article='a_'+article;
var div_article='div_'+article;
var a_edit_add_fb_cmts='a_'+edit_add_fb_cmts;
var div_edit_add_fb_cmts='div_'+edit_add_fb_cmts;

var a_timeline_clear='a_timeline_clear';

var div_timeline='div_timeline';
var dropped_slide_list='dropped_slide_list';

var image_slide='image_slide';
var u2b_slide='u2b_slide';
var article_slide='article_slide';
var fb_slide='fb_slide';
var div_slides_edit_add_images='div_slides_'+edit_add_images;
var div_slides_images_container=div_slides_edit_add_images+'_container';

var div_image_slide='div_'+image_slide;
/*
var div_u2b_slide='div_'+u2b_slide;
var div_art_slide='div_'+article_slide;
var div_fb_slide='div_'+fb_slide;
*/

var parser;

function startup(){
	parser=new DOMParser();
	
	var a_d={ a_edit_add_images:div_edit_add_images, 
			a_u2b:div_u2b,
			a_article:div_article,
			a_edit_add_fb_cmts:div_edit_add_fb_cmts };
	
	$.each(a_d, function(key,value){
		$('#'+value).hide();
		$('#'+key).click(function(){
			$('#'+value).show();
			for (var other in a_d) {
		        if (other != key){
		        	$('#'+a_d[other]).hide();
		        }
			}
			$.each(type_array,function(k,v){
				if (value.indexOf(v)>=0)
					current_type=v;
			});
		});
	});
	
	image_div_content();
	u2b_div_content();
	article_div_content();
	fbcmt_div_content();
	audio_div_content();
	
	$('#'+a_edit_add_images).click();
	
	config_div_timeline();
	
	reload();
	
	init_param();
}

function image_div_content(){
	var ctrl_edit_add_images='ctrl_'+edit_add_images;
	var form_edit_add_images='form_'+edit_add_images;
	var a_image_clearall='a_image_clearall';
	
	$('<div id="'+ctrl_edit_add_images+'"></div>').html(''+
			'<form id="'+form_edit_add_images+'" method="post"'+
			' 	action="./jsp/modules/upload.jsp"'+
			' 	enctype="multipart/form-data">'+
			'<table width="100%"><tr><td width="100%" colspan="2" align="left">'+
			'	<b>add image file(s): <b>'+
			'</td></tr><tr><td align="left">'+
			'	<div style="position:relative;">'+
			'	<div style="position:absolute;top:0px;left:0px;z-index:1;">'+
			'	<input type="text" id="img_txt_fakeupload" style="width:350px; "/>'+
			'	<input type="button" value="Browse"/>'+
			'	</div>'+
			'	<input type="file" name="myfile" class="img_file_browser" style="width:420px"'+
			'		onchange="$(\'#img_txt_fakeupload\').val(this.value);"><br>'+
			'	<input type="submit" value="submit">'+
			'	</div>'+
			'</td</tr>'+
			'</table>'+
			'</form>'+
	'').appendTo('#'+div_edit_add_images);
	/*			
			'	<div id="t_p" class="progress">'+
			'		<div id="t_p_bar" class="bar"></div>'+
			'		<div id="t_p_per" class="percent">0%</div>'+
			'	</div>').appendTo('#'+div_edit_add_images);
	 */
			
	$('#'+div_edit_add_images).append('<br>'+
		'<table height="18"><tr><td width="100" >'+
			'<b>functions: </b><a id="'+a_image_clearall+'">clear all</a>'+	
		'</td><td width="350" align="right">'+
			'<img id="img_progress" src="./images/progress.gif" />'+
		'</td></tr></table>');
	
	$('<div id="'+div_slides_images_container+'" class="container_div"></div>')
	.html('<div id="'+div_slides_edit_add_images+'" class="sub_add_div"></div>')
	.appendTo('#'+div_edit_add_images);
	
	/*
	$('#t_p').css({
		'position': 'relative',
		'width':'446px',
		'border': '1px solid #ddd',
		'padding': '1px',
		'border-radius': '3px',
	});
	
	$('#t_p_bar').css({
		'background-color': '#B4F5B4', 
		'width': '0%', 
		'height':'18px', 
		'border-radius': '3px',
	});
	
	$('#t_p_per').css({
		'position':'absolute', 
		'display':'inline-block', 
		'top':'3px', 
		'left':'48%' 
	});
	
	var bar=$('.bar');
	var percent=$('.percent');
	var status=$('#status');
	*/
	
	$(function(){
		$('#'+form_edit_add_images).ajaxForm({
		    beforeSend: function() {
		        /*
		    	status.empty();
		        var percentVal='0%';
		        bar.width(percentVal);
		        percent.html(percentVal);
		        */
		    	$('#img_progress').show('fast');
		    },
		    uploadProgress: function(event, position, total, percentComplete) {
		        /*
		    	var percentVal=percentComplete + '%';
		        bar.width(percentVal);
		        percent.html(percentVal);
		        */
		    },
			complete: function(xhr) {
				var ret=xhr.responseText.split(splitter);
				if (ret[0] != 1){
					alert('uploading failed' + '\n' + ret[1]);
				}else{
					var temp='';
					for (var i=1;i<ret.length;i++){
						temp+=ret[i]+(i<ret.length-1?splitter:'');
					}
					add_image_slide_to_panel(temp);
				}
				$('#img_progress').hide('fast');
			}
		});
	});

	$('#'+div_slides_edit_add_images).droppable({
		accept: function(d){ 
	        if(d.attr("id").indexOf(div_image_slide)>=0){ 
	            return true;
	        }
		},
		drop:function(event,ui){
			var slide_div=ui.draggable.find('div');
			var slide_id=slide_div.attr('id');
			
			if (!(typeof(slide_id)===undefined_obj)){	
				addback_image_slide_to_panel(slide_id);
			}
			
		}
	});
	
	$('#'+a_image_clearall).click(function(){
		clear_all(TYPE_IMAGE_SLIDE);
	});
	
	$('#img_progress').hide();
}

function fbcmt_div_content(){
	$('<div id="control_'+div_edit_add_fb_cmts+'"></div>').html(''+
			'div4').appendTo('#'+div_edit_add_fb_cmts);
}

function config_div_timeline(){
	$('#'+div_timeline)
	.append('<ul id="'+dropped_slide_list+'"'+
			' class="connectedSortable"></ul>');
	
    $('#'+dropped_slide_list).sortable({
	    connectWith: ".connectedSortable",
	    stop: function(event,ui){
	    	var moved_id=ui.item.attr('id');
	    	if (moved_id.indexOf('li_')==0){
		    	var slide_id=moved_id.replace('li_','');
		    	var new_index=ui.item.index();
		    	if (new_index>=0){
		    		contact_session(TYPE_UPDATE_POSITION, 
							ARRAY_SLIDES,slide_id,new_index);
		    	}
	    	}
	    	/*
	        $('.connectedSortable').each(function() {
	        	
	        });
	        */
	    }

	});
    
	$('#'+div_timeline).droppable({
		accept: function(d){ 
			for (var i=0;i<type_array.length;i++){
				if (d.attr('id').indexOf(type_array[i])>=0)
					return true;
			}
			/*
			$.each(type_array,function(k,v){
				if (d.attr('id').indexOf(v)>=0)
					return true;
			});
			*/
	        /*
			if(d.attr('id').indexOf(div_image_slide)>=0||
	        	d.attr('id').indexOf(div_u2b_slide)>=0||
	        	d.attr('id').indexOf(div_art_slide)>=0||
	        	d.attr('id').indexOf(div_fb_slide)>=0){ 
	            return true;
	        }
	        */
		},
		drop:function(event,ui){
			var dropped_id=ui.draggable.attr('id');
			
			if (dropped_id.indexOf('li_')<0 && 
					check_id(dropped_id,slides[ARRAY_SLIDES])==0){
				if (dropped_id.indexOf(TYPE_IMAGE_SLIDE)>=0){
					add_image_slide_to_timeline(ui.draggable);
				}else {
					add_slide_to_timeline(
							current_type, ui.draggable);
				}
			}
		}
	});
}

function add_image_slide_to_timeline(drag_obj){
	var id=drag_obj.attr('id');
	$('#'+id).remove();

	/** to increase the width of timeline div if there are more slides
	 * than capability of timeslide window */
	if (Object.size(slides[ARRAY_SLIDES]) >= max_slides_on_line){
		var oldw=$('#'+div_timeline).width();
		$('#'+div_timeline).width(oldw+slide_width+additional_part);
	}
	
	var new_li_id='li_'+id;
	/*
	var thumb_img=drag_obj.find('img').attr('src');
	*/
	var thumb_img=drag_obj.css('background-image').replace(/\url|\(|\"|\"|\'|\)/g,'');
	/** for IE, Firefox */
	thumb_img=thumb_img.replace('\"','');
	var data=drag_obj.find('input').val();
	
	$('#'+dropped_slide_list).append(
		$('<li id="'+new_li_id+'" class="ui-state-default"></li>')
		.append(
			add_slide_div(id,thumb_img,data)
	));
	slides[ARRAY_SLIDES][id]=drag_obj;
	contact_session(TYPE_MOVE,ARRAY_IMAGE_SLIDES,id,null);
	
	if (slides[ARRAY_IMAGE_SLIDES][id] != null)
		delete slides[ARRAY_IMAGE_SLIDES][id];
	
	/*
	drag_obj.find('#'+id).css({
		'z-index':'0',
	});
	*/
	add_slide_properties(TYPE_IMAGE_SLIDE,id,
						PROPERTIES_DRAG_EXCLUDE);
}

function add_image_slide_to_timeline_auto(id,content){
	var new_li_id='li_'+id;
	
	/** to increase the width of timeline div if there are more slides
	 * than capability of timeslide window */
	if (Object.size(slides[ARRAY_SLIDES]) >= max_slides_on_line){
		var oldw=$('#'+div_timeline).width();
		$('#'+div_timeline).width(oldw+slide_width+additional_part);
	}

	$('#'+dropped_slide_list).append(
		$('<li id="'+new_li_id+'" class="ui-state-default"></li>')
		.append(content));
	slides[ARRAY_SLIDES][id]=content;
	
	var slide_type=$('#'+id).find('input').
				val().trim().split(splitter)[0];
	
	add_slide_properties(slide_type,id,
				PROPERTIES_DRAG_EXCLUDE);
}


function add_image_slide_to_panel(data){
	var new_image_slide_id=div_image_slide+'_'+slide_idx;
	var exdata=TYPE_IMAGE_SLIDE+splitter+data;
	var thumb=data.split(splitter)[0];
	var new_image_div=add_slide_div(
					new_image_slide_id,thumb,exdata);
	$('#'+div_slides_edit_add_images).prepend(new_image_div);
	slides[ARRAY_IMAGE_SLIDES][new_image_slide_id]=new_image_div;
	
	add_slide_properties(TYPE_IMAGE_SLIDE,
			new_image_slide_id,PROPERTIES_DRAG_INCLUDE);
	
	contact_session(TYPE_ADD,ARRAY_IMAGE_SLIDES,
			new_image_slide_id,new_image_div);
	
	slide_idx++;
}

function add_image_slide_to_panel_auto(id,content){
	$('#'+div_slides_edit_add_images).prepend(content);
	add_slide_properties(TYPE_IMAGE_SLIDE,id,
						PROPERTIES_DRAG_INCLUDE);
	slides[ARRAY_IMAGE_SLIDES][id]=content;
}

function addback_image_slide_to_panel(slide_id){
	var added_div=(slides[ARRAY_SLIDES][slide_id].jquery?
			slides[ARRAY_SLIDES][slide_id].clone():
				slides[ARRAY_SLIDES][slide_id]);
	
	if (slides[ARRAY_SLIDES][slide_id] != null)
		delete slides[ARRAY_SLIDES][slide_id];
	$('#li_'+slide_id).remove();
	
	$('#'+div_slides_edit_add_images)
	.append(added_div);
	slides[ARRAY_IMAGE_SLIDES][slide_id]=added_div;
	
	contact_session(TYPE_MOVEBACK,
			ARRAY_IMAGE_SLIDES,slide_id,null);
	
	add_slide_properties(TYPE_IMAGE_SLIDE,
			slide_id,PROPERTIES_DRAG_INCLUDE);
}

function add_slide_properties(slide_type,div_id,type){
	if (type==PROPERTIES_DRAG_INCLUDE){
		$('#'+div_id).draggable({ 
	        helper: 'clone',
	        start : function() {
	        		this.style.display="none";
	        	},
	        stop: function() {
	        		this.style.display="";
	        	},
	    	placeholder: 'placeholder',
	        forcePlaceholderSize: true,
		});	
	}
	
	if (slide_type!=TYPE_U2B_SLIDE){
		var thumb_img=$('#'+div_id).
			css('background-image').
			replace(/\url|\(|\"|\"|\'|\)/g,'');
		
		$.ajax({
			url:thumb_img,
			type:'HEAD',
			error:
				function(){
					$('#'+div_id).css('background-image',
							'url(./images/no_image.png)');
				},
		});
	}	
	
	$('#slide_ctrl_'+div_id).hide();
	$('#'+div_id).mouseenter(function(){
		$('#slide_ctrl_'+div_id).show('fast');
	}).mouseleave(function() {
		$('#slide_ctrl_'+div_id).hide('fast');
	});
}

function add_slide_div(div_id,thumb_img,data){
	var type=data.split(splitter)[0];
	var pdata=$.trim(data);
	return ''+
		'<div id="'+div_id+'" class="slide_info" style="background-image: url('+thumb_img+');">'+
		'<span id="slide_ctrl_'+div_id+'" class="sub_control_slide_span">'+
		'<a><img src="./images/slidepreview.png" width="15px" alt="preview"></a>'+
		'<a id="a_'+div_id+'" onclick="open_slide_editor(\''+div_id+'\',\''+pdata+'\');"><img src="./images/slideedit.png" width="15px" alt="edit"></a>'+
		'<a onclick="remove_slide(\''+div_id+'\',\''+type+'\');"><img src="./images/slideclose.png" width="15px" alt="close"></a>'+
		'</span>'+
		'<input type="hidden" value="'+pdata+'">'+
		/*
		'<span id="slide_img_'+div_id+'" class="sub_image_slide_span">'+
		'<img src="'+thumb_img+'" width="'+width_img+'px" height="'+width_img+'px"/>'+ 
		'<input type="hidden" value="'+data+'">'+
		'</span>'+
		*/
		'</div>';
}

function remove_all_timeline(){
	$.each(slides[ARRAY_SLIDES],function(k,v){
		$('#li_'+k).remove();
	});
	$('#'+div_timeline).width(TIMELINE_WIDTH);
	slides[ARRAY_SLIDES]={};
	contact_session(TYPE_CLEAR,ARRAY_SLIDES,null,null);
}

function reload(){
	contact_session(TYPE_RETRIEVE_ALL, 
				null, null, null);
}

/**
 * this function make an ajax call to server, ask for updating 
 * corresponding data stored in session synchronously.
 * @param type
 * @param list
 * @param id
 * @param content
 */
function contact_session(type,list,id,content){
	var ctype='add';
	if (type==TYPE_ADD){
		ctype='add';
	}else if (type==TYPE_REMOVE){
		ctype='remove';
	}else if (type==TYPE_REPLACE){
		ctype='replace';
	}else if (type==TYPE_UPDATE){
		ctype='update';
	}else if (type==TYPE_UPDATE_POSITION){
		ctype='update-pos';
	}else if (type==TYPE_MOVE){
		ctype='move';
	}else if (type==TYPE_MOVEBACK){
		ctype='moveback';
	}else if (type==TYPE_RETRIEVE_ALL){
		ctype='retrieve';
	}else if (type=TYPE_CLEAR){
		ctype='clear';
	}
	
	$.ajax({
		url: './jsp/modules/session.jsp',
		data: {
			'type':ctype,
			'list':list,
			'id':id,
			'content':content
		},
		   
		type: 'post',
		success:function(data){
			if (type != TYPE_RETRIEVE_ALL)
				return;
			
			var arr=jQuery.parseJSON(data);
			var elm=null,e=null;
			var max_id=0,currIdx=0;
			var k=null,v=null;
			
			$.each(arr,function(key, arr_val){
				$.each(arr_val,function(){
					e=this.split(server_splitter);
					k=e[0];
					v=e[1];
					switch(key){
						case ARRAY_SLIDES:{
							add_image_slide_to_timeline_auto(k,v);
							break;
						}
						case ARRAY_IMAGE_SLIDES:{
							add_image_slide_to_panel_auto(k,v);
							break;
						}
						case ARRAY_U2B_SLIDES:{
							add_slide_to_panel_auto(TYPE_U2B_SLIDE,k,v);
							break;
						}
						case ARRAY_ARTICLE_SLIDES:{
							add_slide_to_panel_auto(TYPE_ARTICLE_SLIDE,k,v);
							break;
						}
						case ARRAY_FB_SLIDES:{
//							fbslides[k]=v;
							break;
						}
						case ARRAY_AUDIO_SLIDE:{
							add_audio_graph_auto(k,v);
							break;
						}
					}
					elm=k.split('_');
					currIdx=parseInt(elm[elm.length-1]);
					if (max_id < currIdx)
						max_id=currIdx;
				});
				/*
				$.each(arr_val,function(k, v){
					switch(key){
						case ARRAY_SLIDES:{
							add_image_slide_to_timeline_auto(k,v);
							break;
						}
						case ARRAY_IMAGE_SLIDES:{
							add_image_slide_to_panel_auto(k,v);
							break;
						}
						case 'u2bslides':{
							u2bslides[k]=v;
							break;
						}
						case 'artslides':{
							artslides[k]=v;
							break;
						}
						case 'fbslides':{
							fbslides[k]=v;
							break;
						}
					}
					elm=k.split('_');
					currIdx=parseInt(elm[elm.length-1]);
					if (max_id < currIdx)
						max_id=currIdx;
				});
				*/
			});
			slide_idx=max_id+1;
		},		
	});
}

function init_properties(){

}

function check_id(key,arr){
	var ret=0;
	$.each(arr,function(k,v){
		if ($.trim(k)==$.trim(key))
			ret=1;
	});
	return ret;
}